package com.ruijie.acl.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.annotations.Transactional;
import org.springframework.util.Assert;

import com.ruijie.acl.AccessGroup;
import com.ruijie.acl.Ace;
import com.ruijie.acl.AclDevice;
import com.ruijie.acl.AclDeviceAccessGroup;
import com.ruijie.acl.AclDeviceTimeRange;
import com.ruijie.acl.AclInterface;
import com.ruijie.acl.TimeInfo;
import com.ruijie.acl.TimeRange;
import com.ruijie.acl.task.loader.TaskLoadAclDeviceInfo;
import com.ruijie.acl.task.model.AccessGroupInfo;
import com.ruijie.acl.task.model.AclDeviceInfo;
import com.ruijie.acl.task.model.AclInterfaceInfo;
import com.ruijie.acl.task.model.TimeRangeInfo;
import com.ruijie.acl.utils.AclEntityUtil;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.batch.plan.PlanParameters;
import com.ruijie.batch.task.ItemProcessResult;
import com.ruijie.emp.device.Device;
import com.ruijie.emp.device.DeviceInterface;
import com.ruijie.emp.system.DeviceVendor;
import com.ruijie.emp.system.role.internal.UserRoleUtil;
import com.ruijie.emp.system.role.type.PurviewEnum;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.utils.StringUtils;

/**
 * <p>
 * Title: ACL设备服务实现类
 * 
 * </p>
 * <p>
 * Description: 为ACL设备模块提供逻辑处理，以及数据库的操作。
 * 
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-07-15
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */
public class AclDeviceServiceImpl extends AclHibernateEntityExtendDao<AclDevice> implements
		AclDeviceService {

	private TimeRangeService timeRangeService;
	private TimeInfoService timeInfoService;
	private DeviceTimeRangeService deviceTimeRangeService;
	private AccessGroupService accessGroupService;
	private AceService aceService;
	private DeviceAccessGroupService deviceAccessGroupService;
	private AclInterfaceService aclInterfaceService;
	private TaskLoadAclDeviceInfo taskLoadAclDeviceInfo;

	/**
	 * 分页查询
	 * 
	 * @param aclDevice
	 *            ACL设备
	 * @param vendor
	 *            厂商
	 * @param pageNo
	 *            页数
	 * @param pageSize
	 *            每页显示的记录数
	 * @return ACL组列表
	 * 
	 */
	@Override
	@SuppressWarnings("unchecked")
	public Page pageQuery(AclDevice aclDevice, DeviceVendor vendor, int pageNo, int pageSize) {

		Assert.notNull(aclDevice);
		Criteria mainCriteria = createCriteria(AclDevice.class);
		Criteria criteria = createCriteria(Device.class);

		boolean isSelect = false;

		if (aclDevice.getDevice().getName() != null && !"".equals(aclDevice.getDevice().getName())) {
			criteria.add(Restrictions.like("name", aclDevice.getDevice().getName(),
					MatchMode.ANYWHERE));
			isSelect = true;
		}
		if (aclDevice.getDevice().getIp() != null && !"".equals(aclDevice.getDevice().getIp())) {
			criteria.add(Restrictions.or(Restrictions.like("ip", aclDevice.getDevice().getIp(),
					MatchMode.ANYWHERE), Restrictions.sqlRestriction(
					" this_.device_id in ( select device_id from et_ipaddress where ip like ? ) ",
					"%" + aclDevice.getDevice().getIp() + "%", Hibernate.STRING)));
			isSelect = true;
		}

		if (aclDevice.getDevice().getDeviceModel() != null
				&& !StringUtils.isNullOrEmpty(aclDevice.getDevice().getDeviceModel().getName())) {
			criteria.createCriteria("deviceModel", "model").add(
					Restrictions.like("model.name", aclDevice.getDevice().getDeviceModel()
							.getName(), MatchMode.ANYWHERE));
			isSelect = true;
		}

		if (aclDevice.getDevice().getDeviceType() != null) {
			criteria.add(Restrictions.eq("deviceType", aclDevice.getDevice().getDeviceType()));
			isSelect = true;
		}
		if (null != vendor) {
			if (aclDevice.getDevice().getDeviceModel() == null
					|| StringUtils.isNullOrEmpty(aclDevice.getDevice().getDeviceModel().getName()))
				criteria.createAlias("deviceModel", "model");
			criteria.createAlias("model.deviceSeries", "deviceSeries");
			criteria.createAlias("deviceSeries.vendor", "vendor");
			criteria.add(Restrictions.eq("vendor.id", vendor.getId()));
			isSelect = true;
		}
		
		//-----------------add by sinyee --------------------
		mainCriteria.add(Restrictions.sqlRestriction(UserRoleUtil.getSQLNoAnd("this_", "device_id"))); 
		criteria.add(Restrictions.sqlRestriction(UserRoleUtil.getSQLNoAnd("this_", "device_id"))); 

		if (isSelect) {
			List<Device> deviceList = criteria.list();
			if (deviceList != null && deviceList.size() > 0){
				mainCriteria.add(Restrictions.in("device", deviceList));
			}else{
				mainCriteria.add(Restrictions.eq("device.id", -1L));
			}
		}

		// 是否已部署ACL
		if (aclDevice.getAclflag() != null) {
			Criterion isChangedCriterion = null;
			if (aclDevice.getAclflag()) {
				isChangedCriterion = Restrictions.eq("aclflag", aclDevice.getAclflag());
			} else {
				isChangedCriterion = Restrictions.or(Restrictions.eq("aclflag", aclDevice
						.getAclflag()), Restrictions.isNull("aclflag"));
			}
			mainCriteria.add(isChangedCriterion);
		}
		
		return pagedQuery(mainCriteria, pageNo, pageSize);
	}

	/**
	 * 根据设备取得ACL设备
	 * 
	 * @param device
	 *            设备
	 * @return ACL设备
	 */
	@SuppressWarnings("unchecked")
	public AclDevice getByDevice(Device device) {
		Assert.notNull(device);
		AclDevice aclDevice = null;
		Criteria criteria = createCriteria(AclDevice.class);
		criteria.add(Restrictions.eq("device", device));
		List<AclDevice> list = (List<AclDevice>) criteria.list();
		if (list != null && list.size() > 0) {
			aclDevice = list.get(0);
		}
		return aclDevice;
	}

	/**
	 * 根据设备ID取得ACL设备
	 * 
	 * @param id
	 *            设备ID
	 * @return ACL设备
	 */
	@SuppressWarnings("unchecked")
	public AclDevice getByDeviceId(Long deviceId) {
		Assert.notNull(deviceId);
		AclDevice aclDevice = null;
		Criteria criteria = createCriteria(AclDevice.class);
		criteria.add(Restrictions.eq("device.id", deviceId));
		List<AclDevice> list = (List<AclDevice>) criteria.list();
		if (list != null && list.size() > 0) {
			aclDevice = list.get(0);
		}
		return aclDevice;
	}

	/**
	 * 从设备中导入ACL设备信息
	 * 
	 * @param device
	 *            设备
	 * @return 异常对象(正确时返回null)
	 */
	public BusinessException loadInfo(Device device) {
		BusinessException bex = null;
		try {
			AclDevice aclDevice = loadAclDevice(device);
			if (aclDevice == null) {
				throw new BusinessException("device_import_message_ascode_diff");
			}
		} catch (BusinessException ex) {
			bex = ex;
		}
		return bex;
	}

	/**
	 * 同步ACL设备
	 * 
	 * @param device
	 *            设备
	 * @return ACL设备
	 */
	public AclDevice syncAclDevice(Device device) {
		AclDevice aclDevice = this.getByDevice(device);
		if (aclDevice == null) {
			throw new BusinessException("acl_device_not_find");
		}
		return loadAclDevice(device);
	}

	/**
	 * 从设备中导入ACL设备信息
	 * 
	 * @param device
	 *            设备
	 * @return ACL设备信息
	 */
	@Transactional
	public AclDevice loadAclDevice(Device device) {
		Assert.notNull(device);
		PlanParameters parameters = new PlanParameters();
		try {
			// 如果为正式环境
			if (AclUtil.CONFIG_RELEASE_STATE) {
				ItemProcessResult itemProcResult = taskLoadAclDeviceInfo.processItem(device,
						parameters);
				if (itemProcResult == null) {
					// 如果返回的对象不存在，则报错。
					throw new BusinessException("acl_import_error_notexist");
				} else if (!itemProcResult.getExecuted() || !itemProcResult.getSuccess()) {
					throw new BusinessException(itemProcResult.getDesc());
				}

				if (itemProcResult.getResultObject() != null) {
					AclDeviceInfo aclDeviceInfo = (AclDeviceInfo) itemProcResult.getResultObject();
					// ACL设备保存
					AclDevice aclDevice = null;
					aclDevice = this.getByDevice(device);
					if (aclDevice == null) {
						aclDevice = new AclDevice();
					} else {
						// 删除ACL设备与时间段的多对多关系
						deviceTimeRangeService.deleteByAclDevice(aclDevice);
						// 删除ACL设备与ACL组的多对多关系
						deviceAccessGroupService.deleteByAclDevice(aclDevice);
					}

					if (aclDeviceInfo.getAclInterfaceInfoList() != null
							&& aclDeviceInfo.getAclInterfaceInfoList().size() > 0) {
						aclDevice.setAclflag(true);
					} else {
						aclDevice.setAclflag(false);
					}
					aclDevice.setDevice(device);
					aclDevice.setLastSynTime(new Date());
					this.save(aclDevice);
					this.getSessionFactory().getCurrentSession().flush();
					saveTimeRangeInfo2TimeRange(aclDeviceInfo.getTimeRangeInfoList(), aclDevice);
					saveAccessGroupInfo2AccessGroup(aclDeviceInfo.getAccessGroupInfoList(),
							aclDevice);
					saveAclInterfaceInfo2AclInterface(aclDeviceInfo.getAclInterfaceInfoList(),
							aclDevice);

					return aclDevice;
				}
			}
		} catch (BusinessException bex) {
			throw bex;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
		return null;
	}

	/**
	 * 保存时间段信息
	 * 
	 * @param list
	 *            设备的时间段列表
	 * @param aclDevice
	 *            ACL设备
	 */
	public void saveTimeRangeInfo2TimeRange(List<TimeRangeInfo> list, AclDevice aclDevice) {
		// 遍历TimeRangeInfo处理
		// 取得TimeRange信息
		List<TimeRange> timeRangeList = AclEntityUtil.timeRangeInfoList2TimeRangeList(list);
		TimeRange tempTimeRange = null;
		if (timeRangeList != null && timeRangeList.size() > 0) {
			// 取得所有含当前ACL设备的时间段,用于之后的删除无用时间段
			List<TimeRange> existTimeRangeList = timeRangeService.getByAclDevice(aclDevice);
			for (TimeRange entity : timeRangeList) {
				boolean existTimeRange = false;// 判断时间段是否存在的标志位
				boolean hasSameTimeInfos = true;// 判断时间段中的时间信息是否相同的标志位
				boolean datetimeChanged = false;// 判断时间段中的开始结束时间是否有改变的标志位
				List<TimeInfo> timeInfoList = entity.getTimeInfoList();
				if (timeInfoList == null) {
					timeInfoList = new ArrayList<TimeInfo>();
				}
				// 系统时间段,与设备无差异,没有登记设备信息
				TimeRange timeRangeDb = timeRangeService
						.getByNameWithoutAclDevice(entity.getName());
				// 进行DB存在验证TimeRange
				existTimeRange = timeRangeDb != null;
				if (!existTimeRange) {
					// 不存在时
					// 保存TimeRange,系统和设备的
					entity.setTimeInfos(null);
					entity.setIsChanged(false);
					timeRangeService.save(entity);
					TimeRange entityDevice = entity.clone(null, aclDevice);
					timeRangeService.save(entityDevice);
					if (timeInfoList != null && timeInfoList.size() > 0) {
						// 保存所有TimeInfo,包括系统和设备的
						for (TimeInfo timeInfo : timeInfoList) {
							timeInfoService.save(timeInfo.clone(entity));
							timeInfoService.save(timeInfo.clone(entityDevice));
						}
					}
					tempTimeRange = entity;
				} else {
					// 存在时,取得TimeRange
					// 判断所有TimeInfo是否相同
					hasSameTimeInfos = true;
					List<TimeInfo> timeInfoDBList = timeInfoService.getByTimeRange(timeRangeDb);
					if (timeInfoDBList != null && timeInfoDBList.size() > 0) {
						if (timeInfoDBList.size() != timeInfoList.size()) {
							hasSameTimeInfos = false;
						} else {
							for (TimeInfo timeInfo : timeInfoList) {
								if (!hasSameTimeInfos) {
									break;
								}
								boolean tempHasSame = false;
								for (TimeInfo other : timeInfoDBList) {
									if (timeInfo.equals(other)) {
										tempHasSame = true;
										break;
									}
								}
								hasSameTimeInfos = tempHasSame;
							}
						}
					} else if (timeInfoList.size() > 0) {
						hasSameTimeInfos = false;
					}
					TimeRange timeRangeBak = timeRangeService.getByNameWithAclDevice(entity
							.getName(), aclDevice);
					// 若DB中存在对应的设备时间段,则从列表中删除,表示保留其在DB中
					if (timeRangeBak != null) {
						existTimeRangeList.remove(timeRangeBak);
					}
					// 判断时间段的开始结束时间是否有修改
					if (!AclUtil.equals(entity.getStartDate(), timeRangeDb.getStartDate())
							|| !AclUtil.equals(entity.getEndDate(), timeRangeDb.getEndDate())) {
						datetimeChanged = true;
					}
					// 不同时进行以下处理
					if (!hasSameTimeInfos || datetimeChanged || timeRangeBak == null) {
						boolean newTimeRangeBakFlag = false;
						// 备份一个TimeRange,设置设备
						if (timeRangeBak == null) {
							timeRangeBak = new TimeRange();
							newTimeRangeBakFlag = true;
						} else {
							// 若备份项是已存在的时,先删除与其关联的TimeInfo
							if (!hasSameTimeInfos) {
								timeInfoService.deleteByTimeRange(timeRangeBak);
							}
						}
						// timeRangeBak.setName(entity.getName());
						// timeRangeBak.setIsChanged(entity.getIsChanged());
						// timeRangeBak.setRemark(entity.getRemark());
						// timeRangeBak.setAclDevice(aclDevice);
						timeRangeBak = entity.clone(timeRangeBak, aclDevice);

						timeRangeService.save(timeRangeBak);
						// 修改系统时间段的修改标志位为有修改
						if (!timeRangeDb.getIsChanged() && (!hasSameTimeInfos || datetimeChanged)) {
							timeRangeDb.setIsChanged(true);
							timeRangeService.save(timeRangeDb);
						}
						// 保存所有TimeInfo
						if (!hasSameTimeInfos || newTimeRangeBakFlag) {
							for (TimeInfo timeInfo : timeInfoList) {
								timeInfo.setTimeRange(timeRangeBak);
								timeInfoService.save(timeInfo);
							}
						}
					}
					tempTimeRange = timeRangeDb;
				}
				if (tempTimeRange != null) {
					// 保存多对多关系
					AclDeviceTimeRange aclDeviceTimeRange = new AclDeviceTimeRange();
					aclDeviceTimeRange.setAclDevice(aclDevice);
					aclDeviceTimeRange.setTimeRange(tempTimeRange);
					aclDeviceTimeRange.setIsChanged(!hasSameTimeInfos || datetimeChanged);
					deviceTimeRangeService.save(aclDeviceTimeRange);
				}
				if (existTimeRange && !datetimeChanged) {
					// 修改时间段的重新部署标志
					boolean changeFlag = deviceTimeRangeService
							.existByTimeRangeAndChanged(timeRangeDb);
					if (changeFlag != timeRangeDb.getIsChanged()) {
						timeRangeDb.setIsChanged(changeFlag);
						timeRangeService.save(timeRangeDb);
					}
				}
			}
			// 删除设备中不存在但数据库中存在的时间段
			if (existTimeRangeList != null && existTimeRangeList.size() > 0) {
				for (TimeRange delTimeRange : existTimeRangeList) {
					try {
						//判断更新时间段修改标志位
						TimeRange systemTimeRange = timeRangeService.getByNameWithoutAclDevice(delTimeRange.getName());
						if (systemTimeRange.getIsChanged() && !deviceTimeRangeService.existByTimeRangeAndChanged(systemTimeRange)){
							systemTimeRange.setIsChanged(false);
							timeRangeService.update(systemTimeRange);
						}
						timeRangeService.remove(delTimeRange);
					} catch (Exception ex) {
						logger.error("Remove Device TimeRange Error:" + ex.getMessage());
					}
				}
			}

		}
	}

	/**
	 * 保存ACL组信息
	 * 
	 * @param list
	 *            设备的ACL组列表
	 * 
	 * @param aclDevice
	 *            ACL设备
	 */
	public void saveAccessGroupInfo2AccessGroup(List<AccessGroupInfo> list, AclDevice aclDevice) {
		// 遍历AccessGroupInfo处理
		// 取得AccessGroup信息
		List<AccessGroup> accessGroupList = AclEntityUtil.accessGroupInfoList2AccessGroupList(list);
		AccessGroup tempAccessGroup = null;
		if (accessGroupList != null && accessGroupList.size() > 0) {
			// 取得所有含当前ACL设备的ACL组,用于之后的删除无用ACL组
			List<AccessGroup> existAccessGroupList = accessGroupService.getByAclDevice(aclDevice);
			for (AccessGroup entity : accessGroupList) {
				boolean existAccessGroup = false;
				boolean hasSameAccessGroup = true;
				List<Ace> aceList = entity.getAces();
				if (aceList == null) {
					aceList = new ArrayList<Ace>();
				}
				if (aceList.size() > 0 && aceList.get(0) == null) {
					aceList.remove(0);
				}
				// 系统时间段,与设备无差异,没有登记设备信息
				AccessGroup accessGroupSystem = accessGroupService.getByNameWithoutAclDevice(entity
						.getName());
				// 进行DB存在验证AccessGroup
				existAccessGroup = accessGroupSystem != null;
				if (!existAccessGroup) {
					// 不存在时
					// 保存AccessGroup
					entity.setAces(null);
					entity.setIsChanged(false);
					accessGroupService.save(entity);
					AccessGroup entityDevice = entity.clone(aclDevice);
					accessGroupService.save(entityDevice);
					if (aceList != null && aceList.size() > 0) {
						// 保存所有ACE
						for (Ace ace : aceList) {
							// 存在则设置TimeRange对象
							// 不存在时设置TimeRange为null
							AclUtil.filterAce(ace, entity.getAclType());
							TimeRange tiSystem = timeRangeService.getByNameWithoutAclDevice(ace
									.getTimeRangeName());
							aceService.save(ace.clone(entity, tiSystem));
							aceService.save(ace.clone(entityDevice, timeRangeService
									.getByNameWithAclDevice(ace.getTimeRangeName(), aclDevice)));
							// aceService.save(ace.clone(entityDevice,
							// tiSystem));
						}
					}
					tempAccessGroup = entity;
				} else {
					// 存在时,取得AccessGroup
					// 判断所有ACE是否相同
					hasSameAccessGroup = true;
					if (!entity.getAclType().equals(accessGroupSystem.getAclType())) {
						hasSameAccessGroup = false;
					} else {
						List<Ace> aceSystemList = aceService.getByAccessGroup(accessGroupSystem);
						if (aceSystemList != null && aceSystemList.size() > 0) {
							if (aceSystemList.size() != aceList.size()) {
								hasSameAccessGroup = false;
							} else {
								for (int aceIndex = 0; aceIndex < aceSystemList.size(); aceIndex++) {
									Ace tempAceSystem = aceSystemList.get(aceIndex);
									AclUtil.filterAce(tempAceSystem, entity.getAclType());
									Ace tempAce = aceList.get(aceIndex);
									AclUtil.filterAce(tempAce, entity.getAclType());
									if (!tempAceSystem.equals(tempAce)) {
										hasSameAccessGroup = false;
										break;
									}
								}
							}
						} else if (aceList.size() > 0) {
							hasSameAccessGroup = false;
						}
					}
					AccessGroup accessGroupBak = accessGroupService.getByNameWithAclDevice(entity
							.getName(), aclDevice);
					// 若DB中存在对应的设备ACL组,则从列表中删除,表示保留其在DB中
					if (accessGroupBak != null) {
						existAccessGroupList.remove(accessGroupBak);
					}
					// 不同时进行以下处理
					if (!hasSameAccessGroup || accessGroupBak == null) {
						// 备份一个AccessGroup,设置设备
						if (accessGroupBak == null) {
							accessGroupBak = new AccessGroup();
						} else {
							// 若备份项是已存在的时,先删除与其关联的ACE
							aceService.deleteByAccessGroup(accessGroupBak);
						}
						accessGroupBak.setAclType(entity.getAclType());
						accessGroupBak.setName(accessGroupSystem.getName());
						accessGroupBak.setRemark(accessGroupSystem.getRemark());
						accessGroupBak.setIsChanged(true);
						accessGroupBak.setAclDevice(aclDevice);
						accessGroupService.save(accessGroupBak);
						// 修改系统ACL组的修改标志位为有修改
						if (!accessGroupSystem.getIsChanged() && !hasSameAccessGroup) {
							accessGroupSystem.setIsChanged(true);
							accessGroupService.save(accessGroupSystem);
						}
						// 保存所有的ACE
						for (Ace ace : aceList) {
							// 存在则设置TimeRange对象
							// 不存在时设置TimeRange为null
							AclUtil.filterAce(ace, accessGroupBak.getAclType());
							ace.setTimeRange(timeRangeService.getByNameWithAclDevice(ace
									.getTimeRangeName(), aclDevice));
							ace.setAccessGroup(accessGroupBak);
							aceService.save(ace);
						}
					}
					tempAccessGroup = accessGroupSystem;
				}
				if (tempAccessGroup != null) {
					// 保存多对多关系
					AclDeviceAccessGroup aclDeviceAccessGroup = new AclDeviceAccessGroup();
					aclDeviceAccessGroup.setAccessGroup(tempAccessGroup);
					aclDeviceAccessGroup.setAclDevice(aclDevice);
					aclDeviceAccessGroup.setIsChanged(!hasSameAccessGroup);
					deviceAccessGroupService.save(aclDeviceAccessGroup);
				}
				if (existAccessGroup) {
					// 修改ACL组的重新部署标志
					boolean changeFlag = deviceAccessGroupService
							.existByAccessGroupAndChanged(accessGroupSystem);
					if (changeFlag != accessGroupSystem.getIsChanged()) {
						accessGroupSystem.setIsChanged(changeFlag);
						accessGroupService.save(accessGroupSystem);
					}
				}
			}
			// 删除设备中不存在但数据库中存在的ACL组
			if (existAccessGroupList != null && existAccessGroupList.size() > 0) {
				for (AccessGroup delAccessGroup : existAccessGroupList) {
					try {
						//更新ACL组的修改标志位
						AccessGroup systemGroup = accessGroupService.getByNameWithoutAclDevice(delAccessGroup.getName());
						if (systemGroup.getIsChanged() && !deviceAccessGroupService.existByAccessGroupAndChanged(systemGroup)){
							systemGroup.setIsChanged(false);
							accessGroupService.update(systemGroup);
						}
						accessGroupService.remove(delAccessGroup);
					} catch (Exception ex) {
						logger.error("Remove Device AccessGroup Error:" + ex.getMessage());
					}
				}
			}
		}
	}

	/**
	 * 保存ACL接口信息
	 * 
	 * @param list
	 *            设备的ACL接口列表
	 * @param aclDevice
	 *            ACL设备
	 */
	public void saveAclInterfaceInfo2AclInterface(List<AclInterfaceInfo> list, AclDevice aclDevice) {
		Device device = aclDevice.getDevice();
		// 遍历AclInterfaceInfo处理
		List<DeviceInterface> deviceInterfaceList = aclInterfaceService
				.getInterfaceByDevice(device);
		// 删除所有该设备的ACL接口
		aclInterfaceService.removeByDevice(device);
		for (AclInterfaceInfo info : list) {
			DeviceInterface tempDeviceInterface = null;
			// 根据ifname名称取得DeviceInterface信息进行设置
			if (info.getIfName() != null) {
				for (DeviceInterface deviceInterface : deviceInterfaceList) {
					if (info.getIfName().toLowerCase().equals(
							deviceInterface.getName().toLowerCase())) {
						tempDeviceInterface = deviceInterface;
						break;
					}
				}
			}
			if (tempDeviceInterface == null) {
				return;
			}
			AclInterface entity = new AclInterface();
			// 根据outAccessGroup名称取得AccessGroup信息进行设置
			entity.setOutAccessGroupName(info.getOutAccessGroupName());
			if (info.getOutAccessGroupName() != null) {
				entity.setOutAccessGroup(accessGroupService.getByNameWithoutAclDevice(info
						.getOutAccessGroupName(),aclDevice));
			}
			// 根据inAccessGroup名称取得AccessGroup信息进行设置
			entity.setInAccessGroupName(info.getInAccessGroupName());
			if (info.getInAccessGroupName() != null) {
				entity.setInAccessGroup(accessGroupService.getByNameWithoutAclDevice(info
						.getInAccessGroupName(),aclDevice));
			}
			// 设置接口
			entity.setDeviceInterface(tempDeviceInterface);
			// 设置Device
			entity.setDevice(device);

			aclInterfaceService.save(entity);
		}
	}

	@Override
	@Transactional
	public void remove(AclDevice entity) {
		String hql = "";
		// 取得与此ACL设备关联的ACL组列表
		List<AccessGroup> accessGroupList = deviceAccessGroupService
				.getAccessGroupByAclDevice(entity);
		// 删除ACL设备与ACL组的关联
		hql = "delete from AclDeviceAccessGroup where aclDevice=?";
		this.createQuery(hql, entity).executeUpdate();
		// 更新ACL组列表的修改标志位
		accessGroupService.updateChangeFlagByAccessGroupList(accessGroupList);
		// 取得与此ACL设备关联的时间段列表
		List<TimeRange> timeRangeList = deviceTimeRangeService.getTimeRangeByAclDevice(entity);
		// 删除ACL设备与时间段的关联
		hql = "delete from AclDeviceTimeRange where aclDevice=?";
		this.createQuery(hql, entity).executeUpdate();
		// 更新时间段列表的修改标志位
		timeRangeService.updateChangeFlag(timeRangeList);
		// 删除关联的AclInterface
		hql = "delete from AclInterface where device=?";
		this.createQuery(hql, entity.getDevice()).executeUpdate();
		// 删除关联的ACE
		hql = "delete from Ace where accessGroup.id in (select ag.id from AccessGroup ag where ag.aclDevice=?)";
		this.createQuery(hql, entity).executeUpdate();
		// 删除关联的AccessGroup
		hql = "delete from AccessGroup where aclDevice=?";
		this.createQuery(hql, entity).executeUpdate();
		// 删除关联的TimeInfo
		hql = "delete from TimeInfo where timeRange.id in (select tr.id from TimeRange tr where tr.aclDevice=?)";
		this.createQuery(hql, entity).executeUpdate();
		// 删除关联的TimeRange
		hql = "delete from TimeRange where aclDevice=?";
		this.createQuery(hql, entity).executeUpdate();

		String sql = "delete from t_batch_plan_item_param_values where param_id"
				+ " in (SELECT id FROM t_batch_plan_item_parameters where plan_id"
				+ " in (SELECT id FROM t_batch_plan t where task_id"
				+ " in (SELECT id FROM t_batch_task t where code like 'acl_task_code_plan_distribute_%'))"
				+ " and item_id=?)";// t_batch_plan_item_param_values没有实体类
		this.createSQLQuery(sql, entity.getDevice().getId()).executeUpdate();

		hql = "delete from PlanItem where plan.id "
				+ "in(select bp.id from BatchPlan bp where task.id "
				+ "in(select task.id from Task task where code like 'acl_task_code_plan_distribute_%'))"
				+ " and item=?";
		this.createQuery(hql, entity.getDevice().getId()).executeUpdate();

		hql = "delete from ItemParameters where plan.id "
				+ "in(select bp.id from BatchPlan bp where task.id "
				+ "in(select task.id from Task task where code like 'acl_task_code_plan_distribute_%'))"
				+ " and item=?";
		this.createQuery(hql, entity.getDevice().getId()).executeUpdate();

		hql = "delete from AclPlanParameters where device=?";
		this.createQuery(hql, entity.getDevice()).executeUpdate();

		hql = "delete from AclDevice where id=?";
		this.createQuery(hql, entity.getId()).executeUpdate();

	}

	/**
	 * 按设备名字获取设备
	 * 
	 * @param deviceName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public AclDevice getByName(String deviceName) {
		Assert.notNull(deviceName);
		String hql = "select ad from AclDevice ad,Device d where ad.device=d and d.name=?";
		List result = this.createQuery(hql, deviceName).list();
		if (result != null && result.size() > 0) {
			return (AclDevice) result.get(0);
		}
		return null;
	}

	public TimeRangeService getTimeRangeService() {
		return timeRangeService;
	}

	public void setTimeRangeService(TimeRangeService timeRangeService) {
		this.timeRangeService = timeRangeService;
	}

	public TimeInfoService getTimeInfoService() {
		return timeInfoService;
	}

	public void setTimeInfoService(TimeInfoService timeInfoService) {
		this.timeInfoService = timeInfoService;
	}

	public DeviceTimeRangeService getDeviceTimeRangeService() {
		return deviceTimeRangeService;
	}

	public void setDeviceTimeRangeService(DeviceTimeRangeService deviceTimeRangeService) {
		this.deviceTimeRangeService = deviceTimeRangeService;
	}

	public AccessGroupService getAccessGroupService() {
		return accessGroupService;
	}

	public void setAccessGroupService(AccessGroupService accessGroupService) {
		this.accessGroupService = accessGroupService;
	}

	public AceService getAceService() {
		return aceService;
	}

	public void setAceService(AceService aceService) {
		this.aceService = aceService;
	}

	public DeviceAccessGroupService getDeviceAccessGroupService() {
		return deviceAccessGroupService;
	}

	public void setDeviceAccessGroupService(DeviceAccessGroupService deviceAccessGroupService) {
		this.deviceAccessGroupService = deviceAccessGroupService;
	}

	public AclInterfaceService getAclInterfaceService() {
		return aclInterfaceService;
	}

	public void setAclInterfaceService(AclInterfaceService aclInterfaceService) {
		this.aclInterfaceService = aclInterfaceService;
	}

	public TaskLoadAclDeviceInfo getTaskLoadAclDeviceInfo() {
		return taskLoadAclDeviceInfo;
	}

	public void setTaskLoadAclDeviceInfo(TaskLoadAclDeviceInfo taskLoadAclDeviceInfo) {
		this.taskLoadAclDeviceInfo = taskLoadAclDeviceInfo;
	}
	
	@SuppressWarnings("unchecked")
	@Override
    public List<AclDevice> getAll() {
        Criteria criteria = createCriteria(AclDevice.class);
        
        //-------------------add by sinyee -----------------------
        criteria.add(Restrictions.sqlRestriction(UserRoleUtil.getSQLNoAnd("this_", "device_id"))); 
        
        return criteria.list();
    }

}
